package oop.ex1.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * a subclass that copies a file to a specefied location	
 * @author danalmog
 * @author danielshalev
 */
public class Copy extends Actions {
	File outFile;
	File file;
	/**
	 * a constructor that receives the location to copy the file to
	 * @param file the location of the file
	 * @throws CopyDirExeption indicaters that there is a problem with the dir name
	 */
	public Copy(String path,String outfile,File file) throws CopyDirExeption{
		super(file);
		this.file=file;
		//checks if the dir name is legal
		if(outfile.startsWith("/"))
			throw new CopyDirExeption();
		if(outfile.endsWith("/"))
			outfile.substring(0, outfile.length()-1);
		this.outFile=new File(path+"/"+outfile);
		outFile.mkdirs();
	}
	
	/**
	 * a method that copies a file byte by byte to a specified location
	 * @throws BadFileExeption indicates that there is a problem with one of the files
	 */
	public void doAction() throws BadFileExeption{
		OutputStream output=null;
		InputStream input=null;
		try{
			//creates a new file to copy to
			output=new FileOutputStream(new File(this.outFile.getCanonicalPath()+"/"+file.getName()));
			input=new FileInputStream(file);
			int result;
			//copies the file byte by byte
			while((result=input.read()) != -1){
				output.write(result);
			}
		} catch (IOException ioe) {
			throw new BadFileExeption();
		}
		finally{
			//tries to close the stream to the input file
			try{
				if(input != null)
					input.close();
			}
			catch(IOException e){
				throw new BadFileExeption();
			}
			//tries to close the stream to the output file
			try{
				if(output != null)
					output.close();
			}
			catch(IOException e){
				throw new BadFileExeption();
			}
		} 
	}	
}
